<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="780px" :close-on-click-modal="false"
    :before-close="handleClose">
    <div class="form">
      <!-- 表单输入元件 ----------------------------------------------------------------------------------------->
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="80px" class="rule-form">
        <el-form-item label="选择级别" prop="level">
          <el-select v-model="ruleForm.level" placeholder="请选择等级" @change="handleSelect">
            <el-option v-for="(v, k) in ['厂区', '区域', '位置']" :key="k" :label="v" :value="k" />
          </el-select>
        </el-form-item>
        <!--------------------------------------------选择厂区时---------------------------------------------------------- -->
        <el-form-item v-if="ruleForm.level == 0" label="厂区" prop="levelAc">
          <el-input placeholder="请输入位置" v-model="ruleForm.levelAc" />
        </el-form-item>

        <!-- ----------------------------------------选择区域时------------------------------------------------------------ -->
        <el-form-item v-if="ruleForm.level == 1 || ruleForm.level == 2" label="厂区" prop="levelA">
          <el-select v-model="ruleForm.levelA" placeholder="请选择厂区" @change="handleSelectFactory">
            <el-option v-for="item in regionalismList" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="ruleForm.level == 1" label="区域" prop="levelBc">
          <el-input placeholder="请输入区域" v-model="ruleForm.levelBc" />
        </el-form-item>
        <!-- ----------------------------------------选择位置时------------------------------------------------------------ -->
        <el-form-item v-if="ruleForm.level == 2" label="区域" prop="levelB">
          <el-select v-model="ruleForm.levelB" placeholder="请选择区域">
            <el-option v-for="v in FactoryList || []" :key="v.id" :label="v.label" :value="v.id" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="ruleForm.level == 2" label="位置" prop="levelC">
          <el-input placeholder="请输入位置" v-model="ruleForm.levelC" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" placeholder="请输入备注" v-model="ruleForm.remark" maxlength="50" show-word-limit />
        </el-form-item>
      </el-form>
      <!-- ----------------------------------------------------------------------------------------------------->
    </div>
    <div align="center">
      <el-button type="primary" @click="handleConfirm">提交</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
/** 远程添加，修改，获取单个详性接口，获取selector下拉列表的接口，以及时间转换工具函数等 ------------------------------------------------- */
import { addSort, updateSort, listDetailSort, RegionalList } from '@/api/deviceConsumable/inventory'
/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  level: null,// 级别==>  0：厂区，1：区域，2：位置
  levelAc: null,// 厂区输入
  levelA: null,// 厂区选择
  levelBc: null,// 区域输入
  levelB: null,// 区域选择
  levelC: '',// 位置
  remark: '',// 备注
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */
const SubmitFunction = (val) => {
  if (val.level == 2) {
    //选择厂区,选择区域，输入位置-----------------------
    const data = {
      parentId: val.levelB, //父级ID
      storehouseName: val.levelC, //名称
      level: val.level, //级别（0厂区 1区域 2位置）
      sort: "1", //排序
      remark: val.remark //备注
    }
    return data
  } else if (val.level == 1) {
    //选择厂区,输入区域-------------------------
    const data = {
      parentId: val.levelA, //父级ID
      storehouseName: val.levelBc, //名称
      level: val.level, //级别（0厂区 1区域 2位置）
      sort: "1", //排序
      remark: val.remark //备注
    }
    return data
  } else {
    //输入厂区
    const data = {
      parentId: val.level, //父级ID
      storehouseName: val.levelAc, //名称
      level: val.level, //级别（0厂区 1区域 2位置）
      sort: "1", //排序
      remark: val.remark //备注
    }
    return data
  }
}
export default {
  name: 'Form',
  data () {
    return {
      dialogVisible: false,
      ruleForm: Object.assign({}, ruleForm),
      isUpdateForm: false,
      dialogTitle: '添加仓库',
      regionalismList: [],
      FactoryList: [],
      storehouseId: '',
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        level: [
          { required: true, message: '请选择等级', trigger: 'change' }
        ],
        levelA: [
          { required: true, message: '请选择厂区', trigger: 'change' }
        ],
        levelAc: [
          { required: true, message: '请输入厂区', trigger: 'blur' }
        ],
        levelB: [
          { required: true, message: '请选择区域', trigger: 'change' }
        ],
        levelBc: [
          { required: true, message: '请输入区域', trigger: 'blur' }
        ],
        levelC: [
          { required: true, message: '请输入位置', trigger: 'blur' }
        ]
      }
      /** ----------------------------------------------------------------------------------------------------------------------------- */
    }
  },
  methods: {
    // 选择等级时触发事件---------------------------------------------------------------
    handleSelectList (val) {
      RegionalList({ level: val }).then(({ data }) => {
        // console.log('仓库区域获取列表',data);
        this.regionalismList = data
      })
    },
    handleSelect (val) {
      this.handleSelectList(val)
      this.handleSelectFactory(this.ruleForm.levelA)
      this.ruleForm.levelA = null
      this.ruleForm.levelB = null
      this.ruleForm.levelC = null
    },
    // 选择厂区时触发事件--------------------------------------------------------------
    handleSelectFactory (val) {
      this.ruleForm.levelB = null
      this.ruleForm.levelC = null
      const newFactory = this.regionalismList.filter(item => {
        return item.id == val
      })
      if (newFactory[0]) {
        this.FactoryList = newFactory[0].children
      }
    },
    getParentIdList (tree, nodeId, config) {
      const { children = 'children', id = 'id' } = config || {}
      const toFlatArray = (tree, parentId) => {
        return tree.reduce((t, _) => {
          const child = _[children]
          return [
            ...t,
            parentId ? { ..._, parentId } : _,
            ...(child && child.length ? toFlatArray(child, _[id]) : [])]
        }, [])
      }
      const getIds = flatArray => {
        let ids = [nodeId]
        let child = flatArray.find(_ => _[id] === nodeId)
        while (child && child.parentId) {
          ids = [child.parentId, ...ids]
          child = flatArray.find(_ => _[id] === child.parentId)
        }
        return ids
      }
      return getIds(toFlatArray(tree))
    },
    // 打开表单对话框
    openDialog (id = null) {
      if (id) {
        listDetailSort(id).then(res => {
          this.isUpdateForm = true
          this.dialogTitle = '修改仓库'
          /** 修改时的表单参数赋值 --------------------------------------------------------------------------------------------------------------------- */
          // this.ruleForm = res.data
          this.ruleForm.level = res.data.level * 1
          this.storehouseId = id
          if (res.data.level == 2) {
            //选择厂区,选择区域，输入位置-----------------------
            RegionalList({ level: 3 }).then(({ data }) => {
              this.regionalismList = data
              const rule = this.getParentIdList(data, res.data.parentId)
              this.ruleForm.levelA = rule[0]
              this.handleSelectFactory(rule[0])
              this.ruleForm.levelB = rule[1]
              this.ruleForm.levelC = res.data.storehouseName
            })
          } else if (res.data.level == 1) {
            this.handleSelectList(res.data.level * 1)
            //选择厂区,输入区域-------------------------
            this.ruleForm.levelA = res.data.parentId
            this.ruleForm.levelBc = res.data.storehouseName
          } else {
            //输入厂区
            this.handleSelectList(res.data.level * 1)
            this.ruleForm.levelAc = res.data.storehouseName
          }
          this.dialogVisible = true
        })
      } else {
        this.isUpdateForm = false
        this.dialogTitle = '添加仓库'
        this.dialogVisible = true
      }
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = SubmitFunction(this.ruleForm)
          data.storehouseId = this.storehouseId
          console.log('提交的表单', data)
          if (this.isUpdateForm) {
            updateSort(data).then(() => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.resetForm('ruleForm')
              this.dialogVisible = false
              this.$emit('submit_success')
            })
          } else {
            addSort(data).then(() => {
              this.$message({
                message: '创建成功',
                type: 'success'
              })
              this.resetForm('ruleForm')
              this.dialogVisible = false
              this.$emit('submit_success')
            })
          }
        } else {
          // --------consolelog('数据验证不通过，检查输入表单！')
          return false
        }
      })
    },
    // 重置表单
    resetForm (formName) {

      this.ruleForm = Object.assign({}, ruleForm)
      this.$refs[formName].resetFields()
    },
    /** ---------------------------------------------------------------------------------------------------------------------------------------- */
    // 关闭窗口，重置表单
    handleClose () {
      if (this.isUpdateForm) {
        this.$refs['ruleForm'].resetFields()
      } else {
        this.ruleForm = Object.assign({}, ruleForm)
        this.$refs['ruleForm'].resetFields()
      }
      this.dialogVisible = false
    },
    handleConfirm () {
      this.submitForm('ruleForm')
    },
  }
}
</script>
<style lang="scss" scoped>
.form {
  width: 480px;
  margin-left: auto;
  margin-right: auto;
}

::v-deep .el-select {
  width: 100%;
}
</style>
